package picturesender;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * @author sad
 */
public class WheelPanel extends JPanel {

    private int speed;
    private Timer timer;
    private int angle = 0;
    private int visualSpeed;
    private final int id;

    public int getId() {
        return id;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        if(speed>4){
            speed=4;
        }
        if(speed<-4){
            speed=-4;
        }
        this.speed = speed;
    }

    public WheelPanel(int id) {
        this.id = id;
        Dimension d = new Dimension(13 * 3, 13 * 3);
        setPreferredSize(d);
        setMinimumSize(d);
        setMaximumSize(d);
        addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                visualSpeed = 0;
                stopWheelTimer();
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getButton() == 1) {
                    visualSpeed = 1;
                } else {
                    visualSpeed = -1;
                }
                startWheelTimer();
            }

        });
    }

    private void stopWheelTimer() {
        if (timer != null) {
            timer.stop();
            timer = null;
        }
    }

    public void startWheelTimer() {
        stopWheelTimer();
        timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                processWheelByTimer();
            }
        });

        timer.start();
    }

    private void processWheelByTimer() {
        if (visualSpeed == 0) {
            return;
        }

        if (visualSpeed > 0) {
            angle += 10;
        } else {
            angle -= 10;
        }
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setXORMode(Color.WHITE);
        g.setColor(Color.BLACK);
        g.drawOval(10, 10, getWidth() - 20, getHeight() - 20);
        drawRay(g, getWidth() / 2, getHeight() / 2, getWidth() / 2 - 10, angle);
        drawRay(g, getWidth() / 2, getHeight() / 2, getWidth() / 2 - 10, angle + 90);
        drawRay(g, getWidth() / 2, getHeight() / 2, getWidth() / 2 - 10, angle + 180);
        drawRay(g, getWidth() / 2, getHeight() / 2, getWidth() / 2 - 10, angle + 270);

    }

    private void drawRay(Graphics g, int x, int y, int length, int angle) {
        int tx = (int) (Math.cos(Math.toRadians(angle)) * length + x);
        int ty = (int) (Math.sin(Math.toRadians(angle)) * length + y);
        g.drawLine(x, y, tx, ty);
    }
}
